//
//  ExamQuestionsCollectionViewCell.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/4.
//

#import "ExamQuestionsCollectionViewCell.h"
#import "ExamQuestionsListCell.h"
#import <WebKit/WebKit.h>

@interface ExamQuestionsCollectionViewCell()<UITableViewDelegate,UITableViewDataSource,WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UIView *questionView;
@property(nonatomic,strong)UIView *footerView;
@property(nonatomic,strong)UIButton *checkBtn;
@property(nonatomic,strong)UIView *analysisView;
@property(nonatomic,strong)UILabel *analysisLabel;
@property(nonatomic,strong)UILabel *optionTitleLabel;
@property(nonatomic,strong)WKWebView *titleWebView;
@property(nonatomic,strong)WKWebView *contentWebView;
@property(nonatomic,strong)WKWebView *questionWebView;
@property(nonatomic,strong)WKWebView *readContentWebView;
@property(nonatomic,strong)UIImageView *listenImageView;
@property(nonatomic,strong)UIView *rightView;
@property(nonatomic,strong)UILabel *analysisTitleLabel;
@property(nonatomic,strong)UIView *leftView;

@end

@implementation ExamQuestionsCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    self.backgroundColor = UIColorHex(0xF2F7F6);
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, self.currentAvailableWidth,self.height) style:UITableViewStylePlain];
    self.tableView.backgroundColor = UIColorHex(0xF2F7F6);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"ExamQuestionsListCell") forCellReuseIdentifier:@"ExamQuestionsListCell"];
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:self.tableView];
    
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,54)];
    self.headerView.backgroundColor = UIColorHex(0xF2F7F6);
    //大问题题目
    self.questionView = [[UIView alloc]initWithFrame:CGRectMake(16,14,self.currentAvailableWidth-32,0)];
    self.questionView.layer.cornerRadius = 10;
    self.questionView.layer.masksToBounds = YES;
    self.questionView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.headerView addSubview:self.questionView];
    
    //创建webview
    [self createQuestionWebView];
    

    self.tableView.tableHeaderView = self.headerView;
    
    self.listenImageView = [[UIImageView alloc]initWithFrame:CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+10,20,20)];
    self.listenImageView.image = [UIImage imageNamed:@"test_voice_play"];
    self.listenImageView.backgroundColor = UIColorHex(0xF2F7F6);
    self.listenImageView.userInteractionEnabled = YES;
    [self.headerView addSubview:self.listenImageView];
    UITapGestureRecognizer *listenTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(listenPlayTapGesture)];
    [self.listenImageView addGestureRecognizer:listenTap];
    self.listenImageView.hidden = YES;
    
    
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,72)];
    self.footerView.backgroundColor = UIColorHex(0xF2F7F6);
    self.analysisLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,56,self.currentAvailableWidth-40,0)];
    self.analysisLabel.numberOfLines = 0;
    self.analysisView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,56+20)];
    self.analysisView.backgroundColor = UIColorHex(0xF2F7F6);
    CGFloat left_w = (self.currentAvailableWidth-94)/2.0;
    UILabel *analysisTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(left_w, 20, 94, 20)];
    analysisTitleLabel.font = JPUIFontPingFangSCRegular(15);
    analysisTitleLabel.textColor = KFontGrayColor;
    analysisTitleLabel.textAlignment = NSTextAlignmentCenter;
    analysisTitleLabel.text = @"答案解析";
    [self.analysisView addSubview:analysisTitleLabel];
    self.analysisTitleLabel = analysisTitleLabel;
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(20,29.5, left_w-20,1)];
    leftView.backgroundColor = UIColorHex(0xEBF0EF);
    [self.analysisView addSubview:leftView];
    self.leftView = leftView;
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-left_w,29.5, left_w-20,1)];
    rightView.backgroundColor = UIColorHex(0xEBF0EF);
    [self.analysisView addSubview:rightView];
    self.rightView = rightView;
    [self.analysisView addSubview:self.analysisLabel];
    [self.footerView addSubview:self.analysisView];
    self.analysisView.hidden = YES;
    
    self.checkBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.currentAvailableWidth-16-96,10,96,42)];
    [self.checkBtn setTitle:@"查看解析" forState:UIControlStateNormal];
    [self.checkBtn setTitleColor:KFontBlackColor forState:UIControlStateNormal];
    self.checkBtn.titleLabel.font = JPUIFontPingFangSCRegular(16);
    self.checkBtn.backgroundColor = [UIColor whiteColor];
    self.checkBtn.layer.cornerRadius = 10;
    self.checkBtn.layer.masksToBounds = YES;
    [self.checkBtn addTarget:self action:@selector(checkBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView addSubview:self.checkBtn];
    self.checkBtn.hidden = YES;
    
    self.tableView.tableFooterView = self.footerView;
    
    
}

#pragma mark - 创建大题题目webview 大题内容webview
-(void)createQuestionWebView{
    //大题题目
    NSString *jScript0 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript0 = [[WKUserScript alloc] initWithSource:jScript0 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController0 = [[WKUserContentController alloc] init];
    [wkUController0 addUserScript:wkUScript0];
    WKWebViewConfiguration *wkWebConfig0 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig0.userContentController = wkUController0;
    self.questionWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16, 10, self.currentAvailableWidth - 64,0) configuration:wkWebConfig0];
    self.questionWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.questionWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.questionWebView.UIDelegate = self;
    self.questionWebView.navigationDelegate = self;
    self.questionWebView.scrollView.bounces = NO;
    self.questionWebView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.scrollEnabled = NO;
    self.questionWebView.opaque = NO;
    [self.questionView addSubview:self.questionWebView];
    self.questionView.hidden = YES;
    
    //大题内容
    NSString *jScript2 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jScript2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController2 = [[WKUserContentController alloc] init];
    [wkUController2 addUserScript:wkUScript2];
    WKWebViewConfiguration *wkWebConfig2 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig2.userContentController = wkUController2;
    self.contentWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,CGRectGetMaxY(self.questionView.frame)+14, self.currentAvailableWidth - 32,0) configuration:wkWebConfig2];
    self.contentWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.contentWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.contentWebView.UIDelegate = self;
    self.contentWebView.navigationDelegate = self;
    self.contentWebView.scrollView.bounces = NO;
    self.contentWebView.backgroundColor = [UIColor clearColor];
    self.contentWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.contentWebView.scrollView.scrollEnabled = NO;
    self.contentWebView.opaque = NO;
    [self.headerView addSubview:self.contentWebView];
    self.contentWebView.hidden = YES;
    
    //阅读内容
    NSString *jScript3 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript3 = [[WKUserScript alloc] initWithSource:jScript3 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController3 = [[WKUserContentController alloc] init];
    [wkUController3 addUserScript:wkUScript3];
    WKWebViewConfiguration *wkWebConfig3 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig3.userContentController = wkUController3;
    self.readContentWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+14, self.currentAvailableWidth - 32,0) configuration:wkWebConfig3];
    self.readContentWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.readContentWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.readContentWebView.UIDelegate = self;
    self.readContentWebView.navigationDelegate = self;
    self.readContentWebView.scrollView.bounces = NO;
    self.readContentWebView.backgroundColor = [UIColor clearColor];
    self.readContentWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.readContentWebView.scrollView.scrollEnabled = NO;
    self.readContentWebView.opaque = NO;
    [self.headerView addSubview:self.readContentWebView];
    self.readContentWebView.hidden = YES;
    
    //小问题题目
    NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 32];
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];

    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    self.titleWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+14, self.currentAvailableWidth - 32, 24) configuration:wkWebConfig];
    self.titleWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.titleWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.titleWebView.UIDelegate = self;
    self.titleWebView.navigationDelegate = self;
    self.titleWebView.scrollView.bounces = NO;
    self.titleWebView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.scrollEnabled = NO;
    self.titleWebView.opaque = NO;
    [self.headerView addSubview:self.titleWebView];
    
    
}


#pragma mark - 音频播放点击
-(void)listenPlayTapGesture{
    if (self.delegate && [self.delegate respondsToSelector:@selector(hearingTap:)]){
        [self.delegate hearingTap:self];
    }
}

#pragma mark - 开始播放动画
-(void)startVoiceAnimation{
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:@"listen_play.gif" ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    self.listenImageView.image = [UIImage sd_imageWithGIFData:imageData];
}

#pragma mark - 结束播放动画
-(void)stopVoiceAnimation{
    self.listenImageView.image = [UIImage imageNamed:@"test_voice_play"];
}



-(void)refeshUI{
    
    self.titleWebView.frame = CGRectMake(16,24, self.currentAvailableWidth - 32, 24);
    self.questionWebView.frame = CGRectMake(16,10, self.currentAvailableWidth - 64,0);
    self.contentWebView.frame = CGRectMake(16,24, self.currentAvailableWidth - 32,0);
    self.readContentWebView.frame = CGRectMake(16,24, self.currentAvailableWidth - 32,0);
    self.headerView.backgroundColor = UIColorHex(0xF2F7F6);
    self.footerView.backgroundColor = UIColorHex(0xF2F7F6);
    
    if(self.testType == 4){
        //收藏夹大题全部显示 如果有
        //题目
        if(self.model.name&&![self.model.name isEqualToString:@""]){
            self.questionView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 14px; color: #FF781D;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.name];
            if(![self.model.name containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.name];
            }
            [self.questionWebView loadHTMLString:fullHTML baseURL:nil];
        }else{
            self.questionView.hidden = YES;
        }
        //内容
        if(self.model.bigQuestionContent&&![self.model.bigQuestionContent isEqualToString:@""]){
            self.contentWebView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E; line-height: 2; letter-spacing: 2px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.bigQuestionContent];
            if(![self.model.bigQuestionContent containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.bigQuestionContent];
            }
            [self.contentWebView loadHTMLString:fullHTML baseURL:nil];
        }else{
            self.contentWebView.hidden = YES;
        }
        if(self.model.type.integerValue == 33){
            //听力题
            self.listenImageView.hidden = NO;
        }else{
            self.listenImageView.hidden = YES;
        }
    }else{
        self.listenImageView.hidden = YES;
        //题目
        if(self.model.name&&![self.model.name isEqualToString:@""]&&([self.model.lsort isEqualToString:@"1"]||!self.model.lsort)){
            //只有第一个小题才显示大题
            self.questionView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 14px; color: #FF781D;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.name];
            if(![self.model.name containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.name];
            }
            [self.questionWebView loadHTMLString:fullHTML baseURL:nil];
        }else{
            self.questionView.hidden = YES;
        }
        //内容
        if(self.model.bigQuestionContent&&![self.model.bigQuestionContent isEqualToString:@""]&&([self.model.lsort isEqualToString:@"1"]||!self.model.lsort)){
            //只有第一个小题才显示大题
            self.contentWebView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E; line-height: 2; letter-spacing: 2px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.bigQuestionContent];
            if(![self.model.bigQuestionContent containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.bigQuestionContent];
            }
            [self.contentWebView loadHTMLString:fullHTML baseURL:nil];
        }else{
            self.contentWebView.hidden = YES;
        }
    }
    
    //阅读题内容
    if(self.model.readContent&&![self.model.readContent isEqualToString:@""]){
        self.readContentWebView.hidden = NO;
        NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E; line-height: 2; letter-spacing: 2px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.model.readContent];
        if(![self.model.readContent containsString:@"<p>"]){
            fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.model.readContent];
        }
        [self.readContentWebView loadHTMLString:fullHTML baseURL:nil];
    }else{
        self.readContentWebView.hidden = YES;
    }
    
    
    //小题题目
    NSString *htmlContent = self.model.content?self.model.content:@"<p></p>";
    // 题目序号
    NSString *titleNumber = @"";
    if(self.model.sortId&&![self.model.sortId isEqualToString:@""]){
        titleNumber = [NSString stringWithFormat:@"%@.",self.model.sortId];
    }
    // 查找第一个 <p> 标签的位置
    NSRange pTagRange = [htmlContent rangeOfString:@"<p>"];
    // 根据是否找到 <p> 标签进行处理
    NSString *combinedHTMLContent;
    if (pTagRange.location != NSNotFound) {
        // 找到 <p> 标签，插入序号
        combinedHTMLContent = [htmlContent stringByReplacingCharactersInRange:NSMakeRange(pTagRange.location + pTagRange.length, 0) withString:titleNumber];
    } else {
        // 未找到 <p> 标签，直接在字符串前面拼接序号
        combinedHTMLContent = [NSString stringWithFormat:@"<p>%@%@</p>", titleNumber, htmlContent];
    }

    // 设置样式
    NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 17px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
    NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle, combinedHTMLContent];
    [self.titleWebView loadHTMLString:fullHTML baseURL:nil];

    
    [self refreshAnalysisUIWithModel:self.model];

}

#pragma mark - webview delegate 高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    // 执行 JavaScript 以获取页面内容的高度
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id result, NSError *error) {
        if (!error) {
            CGFloat height = [result doubleValue];
            CGFloat h = height-16;
            if(h < 0){
                h = 0;
            }
            if ([webView isEqual:self.titleWebView]) {
                if(h == 0){
                    webView.frame = CGRectMake(16,0, self.currentAvailableWidth - 32,h);
                    self.titleWebView.hidden = YES;
                }else{
                    webView.frame = CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+24, self.currentAvailableWidth - 32,h);
                    self.titleWebView.hidden = NO;
                }
            }else if ([webView isEqual:self.questionWebView]){
                webView.frame = CGRectMake(16,10,self.currentAvailableWidth - 64,h);
                if(h == 0){
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,0);
                    self.questionView.hidden = YES;
                }else{
                    self.questionView.hidden = NO;
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,h+20);
                }
            }else if ([webView isEqual:self.contentWebView]){
                if(h == 0){
                    webView.frame = CGRectMake(16,0,self.currentAvailableWidth -32,h);
                    self.contentWebView.hidden = YES;
                }else{
                    webView.frame = CGRectMake(16,CGRectGetMaxY(self.questionView.frame)+24,self.currentAvailableWidth -32,h);
                    self.contentWebView.hidden = NO;
                }
            }else if ([webView isEqual:self.readContentWebView]){
                if(h == 0){
                    webView.frame = CGRectMake(16,0,self.currentAvailableWidth -32,h);
                    self.readContentWebView.hidden = YES;
                }else{
                    webView.frame = CGRectMake(16,CGRectGetMaxY(self.contentWebView.frame)+24,self.currentAvailableWidth -32,h);
                    self.readContentWebView.hidden = NO;
                }
            }
            
            CGFloat total_h = [self getTotalHeight];
            self.headerView.frame = CGRectMake(0,0,self.currentAvailableWidth,total_h);
            self.tableView.tableHeaderView = self.headerView;
        } else {
            NSLog(@"获取 WebView 内容高度失败: %@", error.localizedDescription);
        }
    }];
}

#pragma mark - 获取头部高度
-(CGFloat)getTotalHeight{
    
    CGFloat top_h = 0;
    //大题题目
    if(self.questionWebView.height > 0){
        self.questionView.hidden = NO;
        top_h = 14+self.questionView.height+24;
    }else{
        top_h = 24;
        self.questionView.hidden = YES;
    }
    //大题内容
    if(self.contentWebView.height > 0){
        self.contentWebView.hidden = NO;
        self.contentWebView.top = top_h;
        top_h = top_h+self.contentWebView.height+24;
    }else{
        self.contentWebView.hidden = YES;
    }
    
    //阅读内容
    if(self.readContentWebView.height > 0){
        self.readContentWebView.hidden = NO;
        self.readContentWebView.top = top_h;
        top_h = top_h+self.readContentWebView.height+24;
    }else{
        self.readContentWebView.hidden = YES;
    }
    
    //小题题目
    if(self.titleWebView.height > 0){
        self.titleWebView.hidden = NO;
        self.titleWebView.top = top_h;
        top_h = top_h+self.titleWebView.height+24;
    }else{
        self.titleWebView.hidden = YES;
    }
    
    //收藏夹 听力题 播放按钮
    if(self.listenImageView.hidden == NO){
        self.listenImageView.top = top_h-24+10;
        top_h = top_h+30;
    }
    
    return top_h;
    
}


#pragma mark - 富文本转化成只带划线的文本
- (NSAttributedString *)parseHTMLString:(NSString *)htmlString withFont:(UIFont *)font color:(UIColor *)color {
    // 1. 处理转义字符
    NSString *unescapedHTMLString = [self unescapeHTMLString:htmlString];
    // 2. 创建 NSMutableAttributedString
    NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] init];
    // 3. 正则表达式，匹配带有下划线的部分
    NSString *pattern = @"<span style=\"text-decoration: underline;\">(.*?)</span>";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return [[NSAttributedString alloc] initWithString:htmlString attributes:@{NSFontAttributeName: font, NSForegroundColorAttributeName: color}];
    }
    __block NSUInteger lastLocation = 0;
    
    // 4. 设置段落样式为按字符换行
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;  // 设置按字符换行
    
    NSDictionary *normalAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle};
    NSDictionary *underlineAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), NSParagraphStyleAttributeName: paragraphStyle};
    
    // 5. 处理匹配的文本
    [regex enumerateMatchesInString:unescapedHTMLString options:0 range:NSMakeRange(0, unescapedHTMLString.length) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
        // 处理普通文本部分
        if (match.range.location > lastLocation) {
            NSString *normalText = [unescapedHTMLString substringWithRange:NSMakeRange(lastLocation, match.range.location - lastLocation)];
            normalText = [self stripHTMLTags:normalText];
            NSMutableAttributedString *normalAttributedString = [[NSMutableAttributedString alloc] initWithString:normalText attributes:normalAttributes];
            [resultString appendAttributedString:normalAttributedString];
        }
        
        // 处理下划线文本部分
        NSRange underlineRange = [match rangeAtIndex:1];
        NSString *underlineText = [unescapedHTMLString substringWithRange:underlineRange];
        NSMutableAttributedString *underlinedAttributedString = [[NSMutableAttributedString alloc] initWithString:underlineText attributes:underlineAttributes];
        [resultString appendAttributedString:underlinedAttributedString];
        
        lastLocation = match.range.location + match.range.length;
    }];
    
    // 处理剩余的普通文本部分
    if (lastLocation < unescapedHTMLString.length) {
        NSString *remainingText = [unescapedHTMLString substringFromIndex:lastLocation];
        remainingText = [self stripHTMLTags:remainingText];
        NSMutableAttributedString *remainingAttributedString = [[NSMutableAttributedString alloc] initWithString:remainingText attributes:normalAttributes];
        [resultString appendAttributedString:remainingAttributedString];
    }
    
    return resultString;
}

// 移除 HTML 标签的辅助方法
-(NSString *)stripHTMLTags:(NSString *)htmlString {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<[^>]+>" options:0 error:nil];
    NSString *cleanedString = [regex stringByReplacingMatchesInString:htmlString options:0 range:NSMakeRange(0, htmlString.length) withTemplate:@""];
    return cleanedString;
}

// 恢复 HTML 转义字符的辅助方法
- (NSString *)unescapeHTMLString:(NSString *)htmlString {
    NSString *unescapedString = [htmlString stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
    return unescapedString;
}


#pragma mark - 刷新解析界面显示
-(void)refreshAnalysisUIWithModel:(ExamQuestionModel*)model{
    
    if((model.isDone&&[model.isDone isEqualToString:@"1"])||(self.testType == 2)||(self.testType == 3)||(self.testType == 4)){
        //查看了解析
        self.checkBtn.hidden = YES;
        self.analysisView.hidden = NO;
        self.analysisLabel.attributedText = [self changeAnalysisStr:model.analysis?model.analysis:@""];
        CGSize a_size = [self.analysisLabel sizeThatFits:CGSizeMake(self.currentAvailableWidth-40,MAXFLOAT)];
        self.analysisLabel.frame = CGRectMake(20,56,self.currentAvailableWidth-40,a_size.height);
        self.analysisView.frame = CGRectMake(0, 0, self.currentAvailableWidth,a_size.height+56+20);
        self.footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,a_size.height+56+20+93);
       
    }else{
        
        self.analysisView.hidden = YES;
        if(self.testType == 0&&((model.isDone&&[model.isDone isEqualToString:@"0"])||[model.isSelect isEqualToString:@"0"]||model.isSelect.integerValue == 0)){
            self.footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,72+93);
            self.checkBtn.hidden = NO;
        }else{
            self.checkBtn.hidden = YES;
            self.footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,93);
        }
    }
    
    self.tableView.tableFooterView = self.footerView;
    [self.tableView reloadData];
    
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ExamQuestionsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExamQuestionsListCell"];
    cell.row = indexPath.row;
    cell.currentAvailableWidth = self.currentAvailableWidth;
    if(indexPath.row < self.model.questionOptions.count){
        ExamQuestionOptionsModel *qmodel = self.model.questionOptions[indexPath.row];
        if((self.model.doAnswer&&![self.model.doAnswer isEqualToString:@""]&&self.model.isDone&&[self.model.isDone isEqualToString:@"1"])||(self.testType == 2)||(self.testType == 3)||(self.testType == 4)){
            //有答题 直接显示答案和对错
            if([self.model.correct isEqualToString:@"1"]){
                //正确
                if([self.model.answer isEqualToString:qmodel.optionKey]){
                    cell.type = 2;
                }else{
                    cell.type = 0;
                }
            }else{
                //错误
                if([self.model.doAnswer isEqualToString:qmodel.optionKey]){
                    cell.type = 3;
                }else{
                    if ([self.model.answer isEqualToString:qmodel.optionKey]){
                        cell.type = 2;
                    }else{
                        cell.type = 0;
                    }
                }
            }
        }else{
            //没有答题
            if(self.model.isDone&&[self.model.isDone isEqualToString:@"0"]){
                //做题的时候选择过
                if([self.model.doAnswer isEqualToString:qmodel.optionKey]){
                    cell.type = 1;
                }else{
                    cell.type = 0;
                }
            }else{
                cell.type = 0;
            }
        }
        
        cell.model = qmodel;

    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if([self.model.isSelect isEqualToString:@"1"]||self.model.isSelect.integerValue == 1){
        return self.model.questionOptions.count;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ExamQuestionsListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(self.testType == 0||self.testType == 1){
        if (!(self.model.isDone&&[self.model.isDone isEqualToString:@"1"])){
            //没有答案就能点击
            ExamQuestionOptionsModel *qmodel = self.model.questionOptions[indexPath.row];
            [cell animateBgViewWithCompletion:^{
                if (self.delegate && [self.delegate respondsToSelector:@selector(answerQuestionTap:andOptionsModel:)]){
                    [self.delegate answerQuestionTap:self andOptionsModel:qmodel];
                }
            }];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < self.model.questionOptions.count){
        ExamQuestionOptionsModel *qmodel = self.model.questionOptions[indexPath.row];
        NSInteger type = 0;
        if((self.model.doAnswer&&![self.model.doAnswer isEqualToString:@""]&&self.model.isDone&&[self.model.isDone isEqualToString:@"1"])||(self.testType == 2)||(self.testType == 3)||(self.testType == 4)){
            //有答题 直接显示答案和对错
            if([self.model.correct isEqualToString:@"1"]){
                //正确
                if([self.model.answer isEqualToString:qmodel.optionKey]){
                    type = 2;
                }else{
                    type = 0;
                }
            }else{
                //错误
                if([self.model.doAnswer isEqualToString:qmodel.optionKey]){
                    type = 3;
                }else{
                    if ([self.model.answer isEqualToString:qmodel.optionKey]){
                        type = 2;
                    }else{
                        type = 0;
                    }
                }
            }
        }else{
            //没有答题
            if(self.model.isDone&&[self.model.isDone isEqualToString:@"0"]){
                //做题的时候选择过
                if([self.model.doAnswer isEqualToString:qmodel.optionKey]){
                    type = 1;
                }else{
                    type = 0;
                }
            }else{
                type = 0;
            }
        }
        
        CGFloat max_w = self.currentAvailableWidth-32-16-47;
        if(type == 3){
            //显示错误时
            max_w = self.currentAvailableWidth-32-32-47-20;
        }
        
        if(qmodel.optionValue&&[qmodel.optionValue containsString:@"<img src="]){
            //图片
            NSArray *arr = [self extractImageSizeFromHTMLString:qmodel.optionValue];
            if(arr.count == 2){
                NSString *pic_w = arr[0];
                NSString *pic_h = arr[1];
                CGFloat w = pic_w.floatValue;
                CGFloat h = pic_h.floatValue;
                if(w > max_w){
                    w = max_w;
                    h = w*pic_h.floatValue/pic_w.floatValue;
                }
                return h+52;
            }
        }else{
            if(!self.optionTitleLabel){
                self.optionTitleLabel = [[UILabel alloc]init];
                self.optionTitleLabel.numberOfLines = 0;
                self.optionTitleLabel.textColor = KFontBlackColor;
                self.optionTitleLabel.font = JPUIFontPingFangSCRegular(16);
            }
            self.optionTitleLabel.attributedText = [self parseHTMLString:qmodel.optionValue?qmodel.optionValue:@"" withFont:self.optionTitleLabel.font color:self.optionTitleLabel.textColor];
            CGSize size = [self.optionTitleLabel sizeThatFits:CGSizeMake(max_w,MAXFLOAT)];
            if(size.height < 22){
                size.height = 22;
            }
            return size.height+52;
        }
    }
    return 74;
}

#pragma mark - 取出图片宽高
- (NSArray *)extractImageSizeFromHTMLString:(NSString *)htmlString {
    
    NSMutableArray *resultArray = [NSMutableArray arrayWithObjects:@"0", @"0", nil];
    
    NSString *pattern = @"<img[^>]+width\\s*=\\s*\"(\\d+)\"[^>]*height\\s*=\\s*\"(\\d+)\"";
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
    if (error) {
        NSLog(@"正则表达式错误: %@", error.localizedDescription);
        return resultArray;
    }
    
    NSTextCheckingResult *match = [regex firstMatchInString:htmlString options:0 range:NSMakeRange(0, [htmlString length])];
    if (match) {
        if ([match rangeAtIndex:1].location != NSNotFound) {
            NSString *width = [htmlString substringWithRange:[match rangeAtIndex:1]];
            resultArray[0] = width ? width : @"0";
        }
        
        if ([match rangeAtIndex:2].location != NSNotFound) {
            NSString *height = [htmlString substringWithRange:[match rangeAtIndex:2]];
            resultArray[1] = height ? height : @"0";
        }
    }
    
    return resultArray;
}

#pragma mark - 查看解析
-(void)checkBtnClick{
    if(self.testType == 0){
        if (self.delegate && [self.delegate respondsToSelector:@selector(checkQuestionTap:)]) {
            [self.delegate checkQuestionTap:self];
        }
    }
}

-(NSMutableAttributedString*)changeAnalysisStr:(NSString*)str{
    
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:str];

    // 创建一个 NSMutableParagraphStyle 实例来设置行间距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10;  // 设置您想要的行间距

    // 将字体和颜色属性应用到整个字符串
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(15) range:NSMakeRange(0, pStr.length)];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(0, pStr.length)];
    
    // 将段落样式应用到整个字符串
    [pStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, pStr.length)];

    return pStr;
}

@end
